package main

import (
	"fmt"
	"grpc-go-demo/echo"
	"io"
	"log"
	"net"

	"google.golang.org/grpc"
)

type EchoImpl struct {
	echo.UnimplementedEchoServer
}

func (e *EchoImpl) ClientStreamEcho(stream echo.Echo_ClientStreamEchoServer) error {
	for {
		req, err := stream.Recv()
		if err == io.EOF {
			log.Println("client closed")
			return stream.SendAndClose(&echo.EchoResponse{Message: "ok"})
		}

		if err != nil {
			return err
		}
		log.Println("received:", req.GetMessage())
	}
}

func main() {
	listener, err := net.Listen("tcp", ":8080")
	if err != nil {
		log.Fatalln(err.Error())
	}
	defer listener.Close()

	grpcServer := grpc.NewServer()

	echo.RegisterEchoServer(grpcServer, &EchoImpl{})

	fmt.Println("client server start at 8080:")

	grpcServer.Serve(listener)
}
